package com.macro.mall.portal.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.macro.mall.model.UmsMember;
import com.macro.mall.portal.service.UmsMemberService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 程序启动预加载
 *
 * @author: TuDou
 * @create: 2024-10-12 16:55
 *
 **/
@Component
public class RedisHandler implements InitializingBean {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UmsMemberService umsMemberService;

    @Value("${redis.userInfoInitPre.userInfoUserNamePre}")
    private String REDIS_KEY_PREFIX_USER_INFO_USER_NAME_PRE;

    @Value("${redis.userInfoInitPre.userInfoUserPhonePre}")
    private String REDIS_KEY_PREFIX_USER_INFO_USER_PHONE_PRE;


    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public void afterPropertiesSet() throws Exception {
        // 初始化缓存
        // 1.查询商品信息
        List<UmsMember> itemList = umsMemberService.getAllUser();
        // 2.放入缓存
        for (UmsMember item : itemList) {
         /*   // 2.1.item序列化为JSON
            String json = MAPPER.writeValueAsString(item);*/
            // 2.2.存入redis
            setWithBloomFilter(REDIS_KEY_PREFIX_USER_INFO_USER_NAME_PRE,item.getUsername());
            setWithBloomFilter(REDIS_KEY_PREFIX_USER_INFO_USER_PHONE_PRE,item.getPhone());


        }

    }
    /**
     * 设置布隆过滤器中是否存在
     */
    public boolean setWithBloomFilter(String checkItem,String key) {
        int hashValue = Math.abs(key.hashCode());
        long index = (long) (hashValue % Math.pow(2, 32));
        return redisTemplate.opsForValue().setBit(checkItem, index,true);
    }


}
